package com.denlaku.longan.core;

import com.denlaku.longan.SpringContext;
import com.denlaku.longan.service.TenantService;
import com.denlaku.longan.vo.Tenant;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.jspecify.annotations.NonNull;

import java.time.Duration;

/**
 * Tenant缓存
 *
 * @author tianx
 */
public class TenantCacheManager {
    private static final String VALID = "1";

    private static final Cache<@NonNull Long, Tenant> TENANT_CACHE = Caffeine.newBuilder()
            .initialCapacity(5)
            .maximumSize(10000)
            .expireAfterWrite(Duration.ofDays(1))
            .build();

    public static Tenant getTenant(Long tenantId) {
        return TENANT_CACHE.get(tenantId, TenantCacheManager::getValidTenant);
    }

    private static Tenant getValidTenant(Long tenantId) {
        TenantService tenantService = SpringContext.getBean(TenantService.class);
        Tenant tenant = tenantService.get(tenantId);
        if (tenant != null && VALID.equals(tenant.getStatus())) {
            return tenant;
        }
        return null;
    }

    public static void remove(Long tenantId) {
        TENANT_CACHE.invalidate(tenantId);
    }

}
